#!/bin/sh

#
# Test making directories on a FAT file system.
#

. "$(cd "$(dirname "$0")" && pwd)/common.sh"

cat >$CONFIG <<EOF
define(BOOT_PART_OFFSET, 63)
define(BOOT_PART_COUNT, 77238)

mbr mbr-a {
    partition 0 {
        block-offset = \${BOOT_PART_OFFSET}
        block-count = \${BOOT_PART_COUNT}
        type = 0xc # FAT32
        boot = true
    }
}
task complete {
	on-init {
                mbr_write(mbr-a)
                fat_mkfs(\${BOOT_PART_OFFSET}, \${BOOT_PART_COUNT})
                fat_mkdir(\${BOOT_PART_OFFSET}, "test_dir")
                fat_mkdir(\${BOOT_PART_OFFSET}, "test_dir/testdir2")
                fat_mkdir(\${BOOT_PART_OFFSET}, "areallylongfilenamedir")
                fat_mkdir(\${BOOT_PART_OFFSET}, "deleteme")
                fat_rm(\${BOOT_PART_OFFSET}, "deleteme")

                # making a directory that's already a directory should still work
                fat_mkdir(\${BOOT_PART_OFFSET}, "test_dir")
        }
}
EOF

# Create the firmware file, then "burn it"
$FWUP_CREATE -c -f $CONFIG -o $FWFILE
$FWUP_APPLY -a -d $IMGFILE -i $FWFILE -t complete

EXPECTED_OUTPUT_ROOT=$WORK/expected.root
ACTUAL_OUTPUT_ROOT=$WORK/actual.root

cat >$EXPECTED_OUTPUT_ROOT << EOF
 Volume in drive : has no label
 Volume Serial Number is 0022-2DB6
Directory for ::/

test_dir     <DIR>     1980-01-01   0:00
AREALL~1     <DIR>     1980-01-01   0:00  areallylongfilenamedir
        2 files                   0 bytes
                         38 908 928 bytes free

EOF

EXPECTED_OUTPUT_SUBDIR=$WORK/expected.subdir
ACTUAL_OUTPUT_SUBDIR=$WORK/actual.subdir

cat >$EXPECTED_OUTPUT_SUBDIR << EOF
 Volume in drive : has no label
 Volume Serial Number is 0022-2DB6
Directory for ::/test_dir

.            <DIR>     1980-01-01   0:00
..           <DIR>     1980-01-01   0:00
testdir2     <DIR>     1980-01-01   0:00
        3 files                   0 bytes
                         38 908 928 bytes free

EOF

# Check that the root directory looks right
mdir -i $WORK/fwup.img@@32256 > $ACTUAL_OUTPUT_ROOT
diff -i -w $EXPECTED_OUTPUT_ROOT $ACTUAL_OUTPUT_ROOT

# Check that the subdirectory looks right
mdir -i $WORK/fwup.img@@32256 test_dir > $ACTUAL_OUTPUT_SUBDIR
diff -w $EXPECTED_OUTPUT_SUBDIR $ACTUAL_OUTPUT_SUBDIR

# Check the FAT file format using fsck
dd if=$WORK/fwup.img skip=63 count=77238 of=$WORK/vfat.img
$FSCK_FAT $WORK/vfat.img

# Check that the verify logic works on this file
$FWUP_VERIFY -V -i $FWFILE
